
#include "test_jni_hook.h"
#include "jni_hook.h"

static jboolean logEnable;

// 定义原始函数
static jint (*test_jni_original)(JNIEnv *, jobject, jint, jint, jstring, jstring);

static jint
test_jni_hook_proxy(JNIEnv *env, jobject java_this, jint a, jint b, jstring tag, jstring msg) {
    // 先走到代理函数，然后走到原函数
    __android_log_print(ANDROID_LOG_ERROR, "hello", "%s", "test_jni_hook_proxy");
    if (logEnable) {
        return test_jni_original(env, java_this, a, b, tag, msg);
    } else {
        return -1;
    }
}

static jint (*native_jni_log_original)(JNIEnv *, jobject, jint, jint, jstring, jstring);

static jint
native_jni_log_proxy(JNIEnv *env, jobject java_this, jint a, jint b, jstring c, jstring d) {
    //hook 逻辑
    __android_log_print(ANDROID_LOG_ERROR, "hello", "%s", "native_jni_log_proxy");
    if(logEnable){
        //原始函数
        return native_jni_log_original(env, java_this, a, b, c, d);
    }else{
        return -1;
    }
}

JNIEXPORT jint JNICALL
Java_com_example_jnihook_MainActivity_testJniHook(JNIEnv *env, jobject thiz, jint a, jint b,
                                                  jstring tag, jstring msg) {
    const char *str = (*env)->GetStringUTFChars(env, msg, NULL);
    __android_log_print(ANDROID_LOG_ERROR, "hello", "%s %s", "test_jni_hook", str);
    (*env)->ReleaseStringUTFChars(env, msg, str);
}


JNIEXPORT jint JNICALL
Java_com_example_jnihook_MainActivity_hooktest(JNIEnv *env, jobject thiz, jobject method,
                                               jboolean enable) {
    logEnable = enable;
    hook_jni(env, method, (void *) test_jni_hook_proxy, (void **) &test_jni_original);
}

JNIEXPORT void JNICALL
Java_com_example_jnihook_MainActivity_unhooktest(JNIEnv *env, jobject thiz, jobject method) {
    unhook_jni(env, method, test_jni_original);
}


JNIEXPORT jint JNICALL
Java_com_example_jnihook_MainActivity_hookAndroidLogNative(JNIEnv *env, jobject thiz,
                                                           jobject method,jboolean enable) {
    logEnable = enable;
    hook_jni(env, method, (void *) native_jni_log_proxy, (void **) &native_jni_log_original);
}

JNIEXPORT void JNICALL
Java_com_example_jnihook_MainActivity_unHookAndroidLogNative(JNIEnv *env, jobject thiz,
                                                             jobject method) {
    unhook_jni(env, method, native_jni_log_original);
}